package com.hcbd.tdwt.ui.xingyu.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.AudioTrackManager;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ImgSendManager;
import com.hcbd.tdwt.util.AppUtil;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;

import org.jetbrains.annotations.NotNull;

import java.text.MessageFormat;
import java.util.List;


public class MsgAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    private List<UserMessageVO> mList;
    private LayoutInflater mLayoutInflater;
    private OnItemClickListener onItemClickListener;
    private int sendResource;
    private int receiveResource;
    public MsgAdapter(Context context, List<UserMessageVO> list) {
        this.mContext = context;
        this.mList = list;
        mLayoutInflater = LayoutInflater.from(mContext);
        if(BdToolFactory.app_type==BdToolFactory.XY_BG_TYPE||BdToolFactory.app_type==BdToolFactory.XY_PDA_BG_TYPE){
            sendResource=R.layout.send_msg_item;
            receiveResource=R.layout.receiver_msg_item;
        }else{
            sendResource= R.layout.send_msg_item_fuda;
            receiveResource=R.layout.receiver_msg_item_fuda;
        }

    }
    public void setOnItemClickListener(OnItemClickListener listener){
        this.onItemClickListener=listener;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == Constant.RECEIVE_MESSAGE) {
            return new ReceiveItemViewHolder(mLayoutInflater.inflate(receiveResource, parent, false));
        } else {
            return new SendItemViewHolder(mLayoutInflater.inflate(sendResource, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(@NotNull final RecyclerView.ViewHolder holder, final int position) {
        final UserMessageVO message = mList.get(position);
        if (holder instanceof ReceiveItemViewHolder) {
            receiveSet(message,holder,position);
        }else{
            sendSet(message,holder,position);
        }

    }

    //发送ViewHolder
    public void sendSet(UserMessageVO message,RecyclerView.ViewHolder holder,int position){
        SendItemViewHolder sendHolder=((SendItemViewHolder) holder);
        if(message.getMsgType()==Constant.TEXT){
            sendHolder.audioPlayLL.setVisibility(View.GONE);
            sendHolder.content.setVisibility(View.VISIBLE);
            sendHolder.content.setText(message.getContent());
            sendHolder.sendPicProgressLL.setVisibility(View.GONE);
            sendHolder.sendPicProTV.setVisibility(View.GONE);
            sendHolder.pictureIV.setVisibility(View.GONE);
        }else if(message.getMsgType()==Constant.AUDIO){
            sendHolder.audioPlayLL.setVisibility(View.VISIBLE);
            sendHolder.secondsTV.setText(MessageFormat.format("{0}″", message.getSeconds()));
            sendHolder.content.setVisibility(View.GONE);
            sendHolder.pictureIV.setVisibility(View.GONE);
            sendHolder.sendPicProgressLL.setVisibility(View.GONE);
            sendHolder.sendPicProTV.setVisibility(View.GONE);
            sendHolder.audioPlayLL.setOnClickListener(view -> playVoice(message.getContent(),sendHolder.audioPlayImg,position));
        }else if(message.getMsgType()== Constant.PICTURE){
            sendHolder.content.setVisibility(View.GONE);
            sendHolder.audioPlayLL.setVisibility(View.GONE);
            sendHolder.pictureIV.setVisibility(View.VISIBLE);
            sendHolder.pictureIV.setOnClickListener(view -> onItemClickListener.viewPic(message.getContent()));
            Glide.with(mContext).load(message.getContent()).centerCrop().error(R.drawable.error_bg).diskCacheStrategy(DiskCacheStrategy.ALL).into(sendHolder.pictureIV);
            sendHolder.cancelSendBtn.setOnClickListener(v -> {
                message.setStatus(Constant.SEND_MSG_FAIL);
                message.update();
                ImgSendManager.getInstance().clear(Constant.SEND_MSG_FAIL);
                sendHolder.sendPicProgressLL.setVisibility(View.GONE);
                sendHolder.sendPicProTV.setVisibility(View.GONE);
                onItemClickListener.onDel(message,false);
            });
            sendHolder.shutDown.setOnClickListener(v -> sendHolder.sendPicProgressLL.setVisibility(View.GONE));
            // 反了？
            int status = message.getStatus();
            if(status==Constant.SEND_MSG_WAIT){
                sendHolder.sendPicProTV.setVisibility(View.VISIBLE);
                sendHolder.sendPicProgressLL.setVisibility(View.GONE);
                sendHolder.sendPicProTV.setOnClickListener(v -> {
                    sendHolder.sendPicProgressLL.setVisibility(View.VISIBLE);
                    onItemClickListener.showPicProgress(sendHolder.picSize,sendHolder.alreadySent,sendHolder.postTheRest,sendHolder.nextSend);
                });
            }else{
                sendHolder.sendPicProgressLL.setVisibility(View.GONE);
                sendHolder.sendPicProTV.setVisibility(View.GONE);
            }
        }
        sendHolder.sendTime.setText(message.getSendTime());
        if (message.getLongitude() == null) {
            sendHolder.viewPosition.setVisibility(View.GONE);
        }else{
            sendHolder.viewPosition.setVisibility(View.VISIBLE);
            sendHolder.viewPosition.setOnClickListener(view -> onItemClickListener.OnItemMapClickListener(view,message.getLongitude(),message.getLatitude()));
        }
        //发送状态判断
        if(message.getStatus()== Constant.SEND_MSG_FAIL){
            sendHolder.progressBar.setVisibility(View.GONE);
            sendHolder.sendError.setVisibility(View.VISIBLE);
            sendHolder.sendStatusTv.setText("发送失败");
            sendHolder.sendStatusTv.setTextColor(ContextCompat.getColor(mContext,R.color.red));
            sendHolder.sendError.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.OnItemResendClickListener(v,message);
                }
            });
        }else if(message.getStatus()== Constant.SEND_MSG_WAIT){
            sendHolder.progressBar.setVisibility(View.VISIBLE);
            sendHolder.sendError.setVisibility(View.GONE);
            sendHolder.sendStatusTv.setText("发送中");
            sendHolder.sendStatusTv.setTextColor(ContextCompat.getColor(mContext,R.color.gray));
        }else if(message.getStatus()== Constant.SEND_MSG_INBOUND){
            sendHolder.sendError.setVisibility(View.GONE);
            sendHolder.progressBar.setVisibility(View.GONE);
            sendHolder.sendStatusTv.setText("入站成功");
            sendHolder.sendStatusTv.setTextColor(ContextCompat.getColor(mContext,R.color.blue_400));
        }else if(message.getStatus()== Constant.SEND_MSG_RECEIVED){
            sendHolder.sendError.setVisibility(View.GONE);
            sendHolder.progressBar.setVisibility(View.GONE);
            sendHolder.sendStatusTv.setText("接收成功");
            sendHolder.sendStatusTv.setTextColor(ContextCompat.getColor(mContext,R.color.blue_400));
        }else{
            sendHolder.sendError.setVisibility(View.GONE);
            sendHolder.progressBar.setVisibility(View.GONE);
            sendHolder.sendStatusTv.setText("发送成功");
            sendHolder.sendStatusTv.setTextColor(ContextCompat.getColor(mContext,R.color.blue_400));
        }
    }
    //接收方
    public void receiveSet(UserMessageVO message,RecyclerView.ViewHolder holder,int position){
        ReceiveItemViewHolder receiveHolder=((ReceiveItemViewHolder) holder);
        if(message.getMsgType()==Constant.TEXT){
            receiveHolder.audioPlayLL.setVisibility(View.GONE);
            receiveHolder.pictureIV.setVisibility(View.GONE);
            receiveHolder.pictureLL.setVisibility(View.GONE);
            receiveHolder.receivePicProTV.setVisibility(View.GONE);
            receiveHolder.content.setVisibility(View.VISIBLE);
            receiveHolder.content.setText(message.getContent());
        }else if(message.getMsgType()==Constant.AUDIO){
            receiveHolder.audioPlayLL.setVisibility(View.VISIBLE);
            receiveHolder.secondsTV.setText(MessageFormat.format("{0}″", message.getSeconds()));
            receiveHolder.receivePicProTV.setVisibility(View.GONE);
            receiveHolder.pictureIV.setVisibility(View.GONE);
            receiveHolder.pictureLL.setVisibility(View.GONE);
            receiveHolder.content.setVisibility(View.GONE);
            receiveHolder.audioPlayLL.setOnClickListener(view -> playVoice(message.getContent(),receiveHolder.audioPlayImg,position));
        }else if(message.getMsgType()== Constant.PICTURE){
            receiveHolder.content.setVisibility(View.GONE);
            receiveHolder.audioPlayLL.setVisibility(View.GONE);
            receiveHolder.pictureIV.setVisibility(View.VISIBLE);
            receiveHolder.pictureLL.setVisibility(View.VISIBLE);
            receiveHolder.receivePicProTV.setVisibility(View.VISIBLE);
            Glide.with(mContext).load(message.getContent()).centerCrop().error(R.drawable.error_bg).diskCacheStrategy(DiskCacheStrategy.ALL).into(receiveHolder.pictureIV);
            String picSizeStr="<font color='#4682b4'>图片大小</font> <font color='#ff0000'>"+message.getPicSize()+"</font> <font color='#4682b4'>KB</font>";
            receiveHolder.picSize.setText(Html.fromHtml(picSizeStr));
            String alreadySentStr = "<font color='#4682b4'>已接收</font> <font color='#ff0000'>" +
                    message.getReceivedPackets() +
                    "</font> <font color='#4682b4'>/共</font><font color='#ff0000'> " +
                    message.getPicSize() +
                    " </font><font color='#4682b4'>条报文</font>";
            receiveHolder.receivedSeveral.setText(Html.fromHtml(alreadySentStr));
            receiveHolder.pictureIV.setOnClickListener(view -> onItemClickListener.viewPic(message.getContent()));
            receiveHolder.receivePicProTV.setOnClickListener(v -> receiveHolder.pictureLL.setVisibility(View.VISIBLE));
            receiveHolder.shutDown.setOnClickListener(v -> receiveHolder.pictureLL.setVisibility(View.GONE));
        }
        receiveHolder.sendTime.setText(message.getSendTime());
        //经纬度
        if (message.getLongitude() == null) {
            receiveHolder.viewPosition.setVisibility(View.GONE);
        }else{
            receiveHolder.viewPosition.setVisibility(View.VISIBLE);
            receiveHolder.viewPosition.setOnClickListener(view -> onItemClickListener.OnItemMapClickListener(view,message.getLongitude(),message.getLatitude()));
        }
    }
    @Override
    public int getItemViewType(int position) {
        //IO类型(发出/收到)0:收 1:发
        return mList.get(position).getIoType();
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
    @Override
    public long getItemId(int position) {
        return position;
    }


    public interface OnItemClickListener {
        //地图点击事件
        void OnItemMapClickListener(View view, String longitude, String latitude);

        //重新发送点击事件
        void OnItemResendClickListener(View view, UserMessageVO userMessage);
        void showPicProgress(TextView picSize, TextView alreadySent, TextView postTheRest, TextView nextSend);
        void viewPic(String path);
        void onDel(UserMessageVO userMessage,boolean isScr);
    }

    public void notifyData(List<UserMessageVO> list) {
        mList=list;
        notifyDataSetChanged();

    }
    //单条插入刷新
    public void notifyInsert(UserMessageVO userMsg) {
        mList.add(userMsg);
        notifyItemInserted(mList.size()-1);
    }
    private AnimationDrawable anim;
    private int currentIndex=-1;
    public void playVoice(String path,ImageView imageView,int position){
        if(AppUtil.isFastClick(1000)){
            MainApp.getInstance().showMsg("点击过快");
            return;
        }
        if(AudioTrackManager.getInstance().isStart()){
            AudioTrackManager.getInstance().stopPlay();
            if(currentIndex==position){
                currentIndex=-1;
                return;
            }
        }
        currentIndex=position;
        AudioTrackManager.getInstance().startPlay(path, new AudioTrackManager.PlayListener() {
            @Override
            public void start() {
                anim= (AnimationDrawable)imageView.getBackground();
                anim.start();
            }
            @Override
            public void stop() {
                if(anim!=null) {
                    anim.selectDrawable(0);
                    anim.stop();
                }
            }
        });
    }
    /**
     * 收到消息
     */
    class ReceiveItemViewHolder extends RecyclerView.ViewHolder {
        private TextView sendTime;
        private TextView content;
        private LinearLayout viewPosition;
        private LinearLayout audioPlayLL;
        private TextView secondsTV;
        private ImageView audioPlayImg;
        private ImageView pictureIV,shutDown;
        private TextView receivePicProTV,picSize,receivedSeveral;
        private LinearLayout receivePicProLL,receiveTipLL,pictureLL;
        private TextView positionTv;
        public ReceiveItemViewHolder(View itemView) {
            super(itemView);
            sendTime=itemView.findViewById(R.id.send_time);
            content=itemView.findViewById(R.id.message_content);
            viewPosition=itemView.findViewById(R.id.view_position);
            audioPlayLL=itemView.findViewById(R.id.audioPlayLL);
            secondsTV=itemView.findViewById(R.id.secondsTV);
            audioPlayImg=itemView.findViewById(R.id.audioPlayImg);
            pictureIV=itemView.findViewById(R.id.pictureIV);
            receivePicProTV=itemView.findViewById(R.id.receivePicProTV);
            receiveTipLL=itemView.findViewById(R.id.receiveTipLL);
            receivePicProLL=itemView.findViewById(R.id.receive_pic_progress_ll);
            shutDown=itemView.findViewById(R.id.shutDown);
            picSize=itemView.findViewById(R.id.picSize);
            receivedSeveral=itemView.findViewById(R.id.receivedSeveral);
            pictureLL=itemView.findViewById(R.id.pictureLL);
            positionTv=itemView.findViewById(R.id.positionTv);
        }
    }

    /**
     * 发送消息
     */
    class SendItemViewHolder extends RecyclerView.ViewHolder {
        private TextView sendTime;
        private TextView content;
        private LinearLayout viewPosition;
        private ProgressBar progressBar;
        private ImageView sendError;
        private LinearLayout audioPlayLL;
        private TextView secondsTV;
        private TextView positionTv;
        private ImageView audioPlayImg;
        private TextView sendStatusTv;
        private ImageView pictureIV,shutDown;
        private LinearLayout sendPicProgressLL;
        private TextView picSize,alreadySent,postTheRest,nextSend,sendPicProTV;
        private Button cancelSendBtn;
        public SendItemViewHolder(View itemView) {
            super(itemView);
            sendTime=itemView.findViewById(R.id.send_time);
            content=itemView.findViewById(R.id.message_content);
            viewPosition=itemView.findViewById(R.id.view_position);
            positionTv=itemView.findViewById(R.id.positionTv);
            progressBar=itemView.findViewById(R.id.send_progress);
            sendError=itemView.findViewById(R.id.send_error);
            audioPlayLL=itemView.findViewById(R.id.audioPlayLL);
            secondsTV=itemView.findViewById(R.id.secondsTV);
            audioPlayImg=itemView.findViewById(R.id.audioPlayImg);
            pictureIV=itemView.findViewById(R.id.pictureIV);
            sendPicProTV=itemView.findViewById(R.id.sendPicProTV);
            sendPicProgressLL=itemView.findViewById(R.id.send_pic_progress_ll);
            shutDown=itemView.findViewById(R.id.shutDown);
            picSize=itemView.findViewById(R.id.picSize);
            alreadySent=itemView.findViewById(R.id.alreadySent);
            postTheRest=itemView.findViewById(R.id.postTheRest);
            nextSend=itemView.findViewById(R.id.next_send);
            cancelSendBtn=itemView.findViewById(R.id.cancelSendBtn);
            sendStatusTv=itemView.findViewById(R.id.sendStatusTv);
        }
    }
}
